//
//  NetworkHandler.m
//  UI20_NSURLSession
//
//  Created by dllo on 16/4/6.
//  Copyright © 2016年 XWH. All rights reserved.
//

#import "NetworkHandler.h"

@interface NetworkHandler ()<NSURLSessionDataDelegate,NSURLSessionTaskDelegate>

@property (nonatomic, retain) NSMutableData *data;

@end


@implementation NetworkHandler

+(void)neworkHandlerJSONWithUrl:(NSString *)url delegate:(id<NetworkHandleDelegate>)delegate{
    
    NetworkHandler *handler = [[NetworkHandler alloc] init];
    
    handler.delegate = delegate;
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    //Core API:
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:handler delegateQueue:[NSOperationQueue mainQueue]];
    
    
    NSURL *newurl = [NSURL URLWithString:url];
    
    NSURLSessionDataTask  *task = [session dataTaskWithURL:newurl];
    
    [task resume];
}


-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
    self.data = [NSMutableData data];
    completionHandler (NSURLSessionResponseAllow);
    
}


-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
    
    [self.data appendData:data];
    
}


-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    
    id result = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers error:nil];
    
    if ([self.delegate respondsToSelector:@selector(didFinishHandler:)]) {
        [self.delegate didFinishHandler:result];
    }
    
}
@end
